package com.ganzalang.gmall.learning.netty.nio;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;

/**
 * @description: 普通Buffer转成只读Buffer
 * @author: Ganzalang
 * @Date 2021/7/13 9:30
 */
@Slf4j
public class ReadOnlyBuffer {

    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(64);

        for (int i = 0; i < 64; i++) {
            byteBuffer.put((byte) i);
        }

        // 读取缓冲区
        byteBuffer.flip();

        ByteBuffer readOnlyBuffer = byteBuffer.asReadOnlyBuffer();

        // 只读缓冲区的读取
        while (readOnlyBuffer.hasRemaining()) {
            log.info("{}", readOnlyBuffer.get());
        }

        // 只读缓冲区不能再写数据进去，会抛出ReadOnlyBufferException
        readOnlyBuffer.put((byte) 100);
    }
}
